package cn.akwangl.interceptor;

import org.springframework.web.filter.CommonsRequestLoggingFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 将{@link HttpServletRequest}转换为{@link ContentCachingRequestWrapper}包装类,
 * 解决{@link HttpServletRequest#getInputStream()}只能读取一次问题.
 *
 * <a href="https://www.cnblogs.com/Sinte-Beuve/p/13260249.html">解决HttpServletRequest 流数据不可重复读</a>
 *
 * @author youyongkun
 * @date 2022/5/17 20:51
 * @see CommonsRequestLoggingFilter
 * @since 0.0.2
 */
@WebFilter(filterName = "httpServletRequestFilter", urlPatterns = "/*")
public class HttpServletRequestFilter implements Filter {
    private static final String FORM_CONTENT_TYPE = "multipart/form-data";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        if (request instanceof HttpServletRequest) {
            HttpServletRequest requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
            if (contentType != null && contentType.contains(FORM_CONTENT_TYPE)) {
                chain.doFilter(request, response);
            } else {
                chain.doFilter(requestWrapper, response);
            }
            return;
        }
        chain.doFilter(request, response);
    }
}
